﻿using UnityEngine;

public class DensityManager : MonoBehaviour
{
    public float maxDensity = 3f; // Agents per square meter
    public float repulsionForce = 10f;
    
    public float GetDensityAtPosition(Vector3 position, float radius)
    {
        Collider[] agents = Physics.OverlapSphere(position, radius, LayerMask.GetMask("Agents"));
        float area = Mathf.PI * radius * radius;
        return agents.Length / Mathf.Max(0.1f, area);
    }
    
    public Vector3 CalculateDensityRepulsion(Vector3 position, float radius)
    {
        float density = GetDensityAtPosition(position, radius);
        
        if (density > maxDensity)
        {
            // Find direction with lowest density
            Vector3 bestDirection = Vector3.zero;
            float minDensity = float.MaxValue;
            
            // Check 8 directions
            for (int angle = 0; angle < 360; angle += 45)
            {
                float rad = angle * Mathf.Deg2Rad;
                Vector3 dir = new Vector3(Mathf.Cos(rad), 0, Mathf.Sin(rad));
                Vector3 samplePos = position + dir * radius;
                
                float sampleDensity = GetDensityAtPosition(samplePos, radius/2);
                if (sampleDensity < minDensity)
                {
                    minDensity = sampleDensity;
                    bestDirection = dir;
                }
            }
            
            return bestDirection * repulsionForce * (density - maxDensity);
        }
        
        return Vector3.zero;
    }
}